package com.example.pkmedical.Utils;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.util.Log;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class DateUtils {
    private static SimpleDateFormat SDF_NORMAL = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static SimpleDateFormat SDF_SIMPLE = new SimpleDateFormat("yyyyMMdd");
    private static SimpleDateFormat SDF_SIMPLE2 = new SimpleDateFormat("yyyyMMdd");
    private static SimpleDateFormat SDF_SIMPLE4 = new SimpleDateFormat("HH:mm");
    private static SimpleDateFormat SDF_NORMAL5 = new SimpleDateFormat("yyyy-MM-dd");
    private static SimpleDateFormat SDF_NORMAL6 = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    private static SimpleDateFormat SDF_SIMPLE7 = new SimpleDateFormat("HH:mm:ss");
    private static SimpleDateFormat SDF_NORMAL8 = new SimpleDateFormat("MM");
    private static SimpleDateFormat SDF_NORMAL9 = new SimpleDateFormat("dd");
    private static SimpleDateFormat SDF_NORMAL11 = new SimpleDateFormat("yyyy");
    private static SimpleDateFormat SDF_NORMAL10 = new SimpleDateFormat("yyyy年MM月dd日");



    public static final String getTime(long time) {

        return SDF_NORMAL.format(time);

    }

    public static final String getTime4(long time) {

        return SDF_SIMPLE7.format(time);

    }

    public static final String getTime5(long time) {

        return SDF_SIMPLE4.format(time);

    }

    public static final String getSimpleTime(long time) {

        return SDF_SIMPLE.format(time);

    }
    public static final String getTime6(long time) {

        return SDF_NORMAL5.format(time);

    }

    public static final String getTime7(long time) {

        return SDF_NORMAL10.format(time);

    }
    public static final String getSimpleTime2(long time) {

        return SDF_SIMPLE2.format(time);

    }

    public static final String getMonth(long time) {
        String month = SDF_NORMAL8.format(time);
        if (month.startsWith("0")) {
            month = month.replace("0", "");
        }
        return month + "月";

    }
    public static final int getMonth2(long time) {

        return Integer.parseInt(SDF_NORMAL8.format(time));

    }

    public static final String getDay(long time) {


        return SDF_NORMAL9.format(time);

    }

    public static final int getYear(long time) {


        return Integer.parseInt(SDF_NORMAL11.format(time));

    }
    public static final String getSimpleTime5(long time) {

        return SDF_NORMAL5.format(time);

    }

    public static final boolean isBackground(Context context) {
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                if (appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {

                    return true;
                } else {

                    return false;
                }
            }
        }
        return false;
    }

    /**
     * 获取当前本地apk的版本
     *
     * @param mContext
     * @return
     */
    public static final int getVersionCode(Context mContext) {
        int versionCode = 0;
        try {
            //获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = mContext.getPackageManager().
                    getPackageInfo(mContext.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 获取版本号名称
     *
     * @param context 上下文
     * @return
     */
    public static final String getVersionName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().
                    getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }


    public static final boolean isBaiDuInstalledAndSupported(Context context) {

        return isInstalled(context, "com.baidu.BaiduMap");
    }

    public static final boolean isGaoDeInstalledAndSupported(Context context) {

        return isInstalled(context, "com.autonavi.minimap");
    }

    private static boolean isInstalled(Context context, String packageName) {
        PackageManager manager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> installedPackages = manager.getInstalledPackages(0);
        if (installedPackages != null) {
            for (PackageInfo info : installedPackages) {
                if (info.packageName.equals(packageName))
                    return true;
            }
        }
        return false;
    }

    public static final String getStreamliningStr(float f) {

        if (f > 100000) {
            f = f / 10000;
            int scale = 2;//设置位数
            int roundingMode = 4;//表示四舍五入，可以选择其他舍值方式，例如去尾，等等.
            BigDecimal bd = new BigDecimal((double) f);
            bd = bd.setScale(scale, roundingMode);
            f = bd.floatValue();
            return f + "万";
        }

        return f + "";

    }

    public static final String getStreamliningStr(String s) {
        try {
            float f = Float.parseFloat(s);
            if (f > 100000) {
                f = f / 10000;
                int scale = 2;//设置位数
                int roundingMode = 4;//表示四舍五入，可以选择其他舍值方式，例如去尾，等等.
                BigDecimal bd = new BigDecimal((double) f);
                bd = bd.setScale(scale, roundingMode);
                f = bd.floatValue();
                return f + "万";
            }
        } catch (Exception e) {
            return s;
        }
        return s;

    }

    public static final String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return format.format(date);
    }


    public static final String getHourAndMinutes(long date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        return format.format(date);
    }

    public static final String getTime2(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    public static final String getTime2(long time) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(time);
    }

    public static final String getTime3(Date date) {//可根据需要自行截取数据显示
        return SDF_NORMAL6.format(date);
    }

    public static final String getTime3(long date) {//可根据需要自行截取数据显示
        return SDF_NORMAL6.format(date);
    }

    public static final boolean isEffectiveDate(Calendar date, Calendar begin, Calendar end) {
        if (date.getTimeInMillis() == begin.getTimeInMillis()
                || date.getTimeInMillis() == end.getTimeInMillis()) {
            return true;
        }

//        Calendar date = Calendar.getInstance();
//        date.setTime(nowTime);
//
//        Calendar begin = Calendar.getInstance();
//        begin.setTime(startTime);
//
//        Calendar end = Calendar.getInstance();
//        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

    public static final String getPlanTime(long currentTime) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        return format.format(new Date(currentTime));
    }


    /**
     * 判断当前时间是否在[startTime, endTime]区间，注意时间格式要一致
     *
     * @param nowTime   当前时间
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return
     * @author jqlin
     */
    public static final boolean isEffectiveDate2(Date nowTime, Date startTime, Date endTime) {
//        if (nowTime.getTime() == startTime.getTime()
//                || nowTime.getTime() == endTime.getTime()) {
//            return true;
//        }


        if (nowTime.getTime() == startTime.getTime()) {
            return true;
        }
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

    public static final boolean isBetween(String nowStr, String startStr, String endStr) {
        try {
            Date nowTime = SDF_SIMPLE4.parse(nowStr);
            Date startTime = SDF_SIMPLE4.parse(startStr);
            Date endTime = SDF_SIMPLE4.parse(endStr);
            return isEffectiveDate2(nowTime, startTime, endTime);
        } catch (Exception e) {

        }
        return false;
    }


    public static final boolean isBetween2(String nowStr, String startStr, String endStr) {
        try {
            Date nowTime = SDF_NORMAL6.parse(nowStr);
            Date startTime = SDF_NORMAL6.parse(startStr);
            Date endTime = SDF_NORMAL6.parse(endStr);
            return isEffectiveDate2(nowTime, startTime, endTime);
        } catch (Exception e) {

        }
        return false;
    }

    public static final boolean isBetween3(String nowStr, String startStr, String endStr) {
        try {
            Date nowTime = SDF_NORMAL.parse(nowStr);
            Date startTime = SDF_NORMAL.parse(startStr);
            Date endTime = SDF_NORMAL.parse(endStr);
            return isEffectiveDate2(nowTime, startTime, endTime);
        } catch (Exception e) {

        }
        return false;
    }

    public static final boolean isBetween4(String nowStr, String startStr, String endStr) {
        try {
            Date nowTime = SDF_SIMPLE7.parse(nowStr);
            Date startTime = SDF_SIMPLE7.parse(startStr);
            Date endTime = SDF_SIMPLE7.parse(endStr);
            return isEffectiveDate2(nowTime, startTime, endTime);
        } catch (Exception e) {

        }
        return false;
    }

    //当前时间是否在指定时间之后
    public static final boolean isLaterNow(String nowStr, String startStr) {
        try {
            Date nowTime = SDF_SIMPLE4.parse(nowStr);
            Date startTime = SDF_SIMPLE4.parse(startStr);

            return isEffectiveDate3(nowTime, startTime);
        } catch (Exception e) {

        }
        return false;
    }


    public static final boolean isEffectiveDate3(Date nowTime, Date startTime) {
        if (nowTime.getTime() == startTime.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);


        if (date.after(begin)) {
            return true;
        } else {
            return false;
        }
    }


    public static final String secondToTime(int s) {
        int second = s;
        long days = second / 86400;//转换天数
        second = second % 86400;//剩余秒数
        long hours = second / 3600;//转换小时数
        second = second % 3600;//剩余秒数
        long minutes = second / 60;//转换分钟
        second = second % 60;//剩余秒数

        if (s < 60) {
            return second + "秒";
        } else if (s >= 60 && s < 3600) {
            return minutes + "分" + second + "秒";
        }
        if (0 < days) {
            return days + "天，" + hours + "小时" + minutes + "分" + second + "秒";
        } else {
            return hours + "小时" + minutes + "分" + second + "秒";
        }
    }


    /**
     * 两个时间之间相差距离多少天
     *
     * @return 相差天数
     */
    public static final long getDistanceDays(String str1, String str2) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date one;
        Date two;
        long days = 0;
        try {
            one = df.parse(str1);
            two = df.parse(str2);
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff;
            if (time1 < time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            days = diff / (1000 * 60 * 60 * 24);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return days;
    }

    public static final String dateToWeek(String datetime) {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance(); // 获得一个日历
        Date datet = null;
        try {
            datet = f.parse(datetime);
            cal.setTime(datet);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

    public static final int getDayOfWeek() {
        Calendar calendar = Calendar.getInstance();

        return calendar.get(Calendar.DAY_OF_WEEK) - 1;
    }


    public static final int getNativeDayOfWeek() {
        Calendar calendar = Calendar.getInstance();
        int week = calendar.get(Calendar.DAY_OF_WEEK);
        if (week >= 2) {
            week = week - 2;
        } else {
            week = 6;
        }

        return week;
    }
    public static final boolean isHaveToday(String dayArray) {
        if (TextUtils.isEmpty(dayArray)) {
            return false;
        }
        String[] days = dayArray.split(",");

        if (days.length == 0) {
            return false;
        }
        int dayOfWeek = getDayOfWeek();
        String weekStr = "";
        switch (dayOfWeek) {
            case 1:
                weekStr = "week1";
                break;
            case 2:
                weekStr = "week2";
                break;
            case 3:
                weekStr = "week3";
                break;
            case 4:
                weekStr = "week4";
                break;
            case 5:
                weekStr = "week5";
                break;
            case 6:
                weekStr = "week6";
                break;
            case 0:
                weekStr = "week7";
                break;
        }

        if (TextUtils.isEmpty(weekStr)) {
            return false;
        }
        for (int i = 0; i < days.length; i++) {
            if (days[i].equals(weekStr)) {
                return true;
            }
        }

        return false;
    }
//在某一个时间的基础上加N分钟
    public static final String addDateTime(String currentTime, int min) {
        //SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//12小时制
        Date date = null;
        try {
            date = SDF_NORMAL6.parse(currentTime);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (date == null) return "";
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MINUTE, min);
        date = cal.getTime();
        System.out.println("front:" + date);
        cal = null;
        return SDF_NORMAL6.format(date);
    }


    /**
     * 两个时间之间相差距离多少分钟
     *
     * @return 相差天数
     */
    public static final int getDistanceMinutes(long timeStart,long timeEnd) {
if(timeStart==0||timeStart==0){
    return 0;
}
        int min = 0;
        try {


            long diff;
            if (timeStart < timeEnd) {
                diff = timeEnd - timeStart;
            } else {
                diff = timeStart - timeEnd;
            }
            min = (int) (diff / (1000 * 60  ));
        } catch (Exception e) {

            return 0;
        }
        return min;
    }

//时分秒转时间戳
    public static long HMS2Long(String time){
        try {
            Date date = SDF_SIMPLE7.parse(time);
            return date.getTime();
        }catch (Exception e){


        }

        return 0;

    }

    //年月日时分秒转时分秒
    public static String YMDHMS2HMS(String time){
        try {
            Date date = SDF_NORMAL.parse(time);
            return SDF_SIMPLE7.format(date.getTime());
        }catch (Exception e){


        }

        return "";

    }

    public static long   YMDHMS2Long(String str) {
        try {
            Date date = SDF_NORMAL.parse(str);
            return date.getTime();
        }catch (Exception e){


        }

        return 0;

    }


    public static long   YMDHM2Long(String str) {
        try {
            Date date = SDF_NORMAL6.parse(str);
            return date.getTime();
        }catch (Exception e){


        }

        return 0;

    }





    /**
     * 通过指定的年份和月份获取当月有多少天.
     *
     * @param year  年.
     * @param month 月.
     * @return 天数.
     */
    public static int getMonthDays(int year, int month) {
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                return 31;
            case 4:
            case 6:
            case 9:
            case 11:
                return 30;
            case 2:
                if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)){
                    return 29;
                }else{
                    return 28;
                }
            default:
                return -1;
        }
    }

    /**
     * 获取指定年月的 1 号位于周几.
     * @param year  年.
     * @param month 月.
     * @return      周.
     */
    public static int getFirstDayWeek(int year, int month){
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, 0);
        return calendar.get(Calendar.DAY_OF_WEEK);
    }





}
